import { constantRoutes, noProRoutes } from '@/router'
import Layout from '@/layout/index'

const state = {
  routes: [],
  addRoutes: []
}

// 获取所有vue路径
const modules = import.meta.glob('../../views/**/*.vue')

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // 检测为非生产环境时加入工具路由
    const router = noProRoutes.filter(row => {
      const item = routes.find(items => items.path === row.path)
      return !item
    })
    state.routes = constantRoutes.concat(routes).concat(router)
  }
}

const actions = {
  // 生成路由
  generateRoutes({ dispatch, commit }, data = []) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRouter(data, dispatch)
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      const routes = noProRoutes.filter(row => {
        const item = accessedRoutes.find(items => items.path === row.path)
        return !item
      })
      resolve(accessedRoutes.concat(routes))
    })
  }
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, dispatch) {
  return asyncRouterMap.filter(route => {
    // 将菜单类型为按钮的数据过滤
    if (route.type === 3) return false
    // Layout组件特殊处理
    if (route.type === 1) {
      route.component = Layout
    } else {
      route.component = loadView(route.component)
    }
    if (route.label) {
      route.meta = {
        title: route.label,
        icon: route.icon,
        permission: route.permission,
        affix: route.affix === 1,
        isLink: route.isLink === 1,
        activeMenu: route.activeMenu, // 高亮路由path
        port: !route.port ? route.path.split('/:')[0] : route.port // 针对接口地址进行初始赋值
      }
    }
    // 针对缓存生成name
    if (route.path) {
      const names = route.path.split('/')
      route.name = names[names.length - 1].charAt(0).toUpperCase() + names[names.length - 1].slice(1) // 将首字母大写匹配组件name
    }
    // 针对缓存菜单加入缓存数组
    if (route.cache === 1) {
      dispatch('tagsView/addCachedView', route, { root: true })
    }
    route.hidden = route.showStatus !== 1
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, dispatch)
    } else if (route.children && !route.children.length) {
      delete route.children
    }
    return true
  })
}
export const loadView = (view) => { // 路由懒加载
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
